# $Id: xml2dom.tcl 19 2007-08-05 23:17:37Z khomoutov $
# This snippet attempts to combat fsck'ed up XML hublist files
# fetched from http://www.dchublist.com
# This proc intended to be working with tDOM.

# This proc:
# * Opens a given XML file and reads it preamble looking for the
#   encoding declaration;
# * If found, it tries to normalize this value, then reads the whole
#   file in the resulting encoding (so it ends up as a UTF-8 string
#   in the interpreter's memory.
# * It substitutes the encoding to read "UTF-8" instead so the expat
#   parser could go on.

# NOTE that it does NOT work as expected for aforementioned
# hublists since they're fsck'ed up even harder: they use proxibited
# characters like & or < in string resources.
# Patching of such documents seems not worthing the efforts.
# Probably it's simpler to write dumb symbol-by-symbol parser for them.

proc xml2dom fname {
	set fd [open $fname]
	fconfigure $fd -encoding ascii
	set preamble [read $fd 100]
	seek $fd 0
	set ok [regexp {encoding=(['"])([^'"]+)\1} $preamble -> -> enc]
	if {!$ok} {
		return -code error "failed to get XML encoding"
	}
	set enc [string map {windows- cp} $enc]
	fconfigure $fd -encoding $enc

	set xml [regsub {(encoding=['"])[^'"]+(['"])} [read $fd] \\1UTF-8\\2]
	dom parse $xml
}

